package top.nextdoc4j.demo.common.configuration.customizer;

import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.models.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.web.method.HandlerMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局描述定制器 - 处理 sa-token 的注解权限码
 *
 * @author echo
 * @date 2025/01/24 14:59
 */
@Slf4j
@RequiredArgsConstructor
public class GlobalDescriptionCustomizer implements GlobalOperationCustomizer {

    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {

        // 将sa-token 注解数据添加到operation的描述中
        // 权限
        List<String> noteList = new ArrayList<>(new OperationDescriptionCustomizer().getPermission(handlerMethod));

        // 如果注解数据列表为空，直接返回原 operation
        if (noteList.isEmpty()) {
            return operation;
        }
        // 拼接注解数据为字符串
        String noteStr = StrUtil.join("<br/>", noteList);
        // 获取原描述
        String originalDescription = operation.getDescription();
        // 根据原描述是否为空，更新描述
        String newDescription = StringUtils.isNotEmpty(originalDescription)
                ? originalDescription + "<br/>" + noteStr
                : noteStr;

        // 设置新描述
        operation.setDescription(newDescription);
        Map<String, Object> noteMap = operation.getExtensions();
        if (noteMap != null) {
            noteMap.put("x-sa-token", noteList);
        } else {
            noteMap = new HashMap<>();
            noteMap.put("x-sa-token", noteList);
        }
        operation.setExtensions(noteMap);

        return operation;
    }
}
